package dp05.leertaak1.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerConnection
{

    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    public final int PORT = 1337;

    public ServerConnection()
    {

    }

    public String processAction(String input)
    {
        if (isConnected())
        {
            out.println(input);
            String fromServer = null;
            try
            {
                fromServer = in.readLine();
            } catch (IOException e)
            {
                fromServer = "An error occured during your request. Please try again";
                e.printStackTrace();
            }
            return fromServer;
        } else
        {
            return "The server is not connected. Please connect before sending further instructions.";
        }
    }

    public String connect(String host)
    {
        String statusMessage = null;
        if (!isConnected() || socket.isClosed())
        {
            try
            {
                socket = new Socket(host, PORT);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                statusMessage = "Connected to the server.";
            } catch (UnknownHostException e)
            {
                statusMessage = "Unknown host";
            } catch (IOException e)
            {
                statusMessage = "An error occured, please validate your input and try again. Is the server running?";
            }
        } else
        {
            statusMessage = "Already connected to a server. Please disconnect before opening a new connection.";
        }
        return statusMessage;
    }

    public void close() throws IOException
    {
        out.close();
        in.close();
        socket.close();
    }

    public boolean isConnected()
    {
        if (socket != null)
        {
            return socket.isConnected();
        } else
        {
            return false;
        }
    }
}
